package com.system.ad.index.interest;

import com.system.ad.index.IndexAware;
import com.system.ad.utlis.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 兴趣索引服务
 */
@Slf4j
@Component
public class UnitItIndex implements IndexAware<String, Set<Long>> {

    // 根据兴趣标签获取推广单元
    private static Map<String, Set<Long>> itUnitMap = new ConcurrentHashMap<>();
    // 根据推广单元获取兴趣标签
    private static Map<Long, Set<String>> unitItMap = new ConcurrentHashMap<>();

    @Override
    public Set<Long> get(String key) {
        if (StringUtils.isEmpty(key)) {
            return Collections.emptySet();
        }
        // 查找推广单元
        Set<Long> result = itUnitMap.get(key);
        if (result == null) {
            return Collections.emptySet();
        }
        return result;
    }

    @Override
    public void add(String key, Set<Long> value) {
        log.info("itUnitIndex ,before add:{}", itUnitMap);
        // 同时添加到关键字索引和ID索引集合
        // 需要判断key是否存在，创建或直接添加
        Set<Long> unitIdSet = CommonUtils.getterCreate(key, itUnitMap, ConcurrentSkipListSet::new);
        unitIdSet.addAll(value);

        // 循环插入推广单元Id
        for (Long unitId : value) {
            Set<String> its = CommonUtils.getterCreate(unitId, unitItMap, ConcurrentSkipListSet::new);
            its.add(key);
        }
        log.info("itUnitIndex ,after add:{}", itUnitMap);
    }

    @Override
    public void update(String key, Set<Long> value) {
        log.error("it index cat not support update");
    }

    @Override
    public void delete(String key, Set<Long> value) {
        log.info("itUnitIndex ,before delete:{}", itUnitMap);
        //取出需要删除部分
        Set<Long> unitIds = CommonUtils.getterCreate(key, itUnitMap, ConcurrentSkipListSet::new);
        unitIds.removeAll(value);

        // 循环插入推广单元Id
        for (Long unitId : value) {
            Set<String> itTags = CommonUtils.getterCreate(unitId, unitItMap, ConcurrentSkipListSet::new);
            itTags.remove(key);
        }
        log.info("itUnitIndex ,after delete:{}", itUnitMap);
    }


    /**
     * 判断关键字索引是否命中
     *
     * @param unitId
     * @param itTags
     * @return
     */
    public boolean match(Long unitId, List<String> itTags) {
        // 判断索引中是否存在推广单元ID，并且推广关键字不为空
        if (unitItMap.containsKey(unitId) && CollectionUtils.isNotEmpty(unitItMap.get(unitId))) {
            Set<String> unitKeywords = unitItMap.get(unitId);
            //判断关键字是否存在集合中
            return CollectionUtils.isSubCollection(itTags, unitKeywords);
        }
        return false;
    }
}
